#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#Author: alvayang <alvayang@tabex.org>
#Last Change: 
#Description: 

from twisted.enterprise import adbapi

import os
import sys



class GFMSGDB:
    def __init__(self, basename):
        self.dbpath = os.path.join(basename, 'msg.sqlite3')
        self.pool = adbapi.ConnectionPool('sqlite3', database = self.dbpath)
        self.sql_pool = []

    def execute_many(self, sql, callback = None, errorback = None):
        self.sql_pool.append(sql)

    def commit_many(self):
        return self.pool.runInteraction(self._commit_many)

    def _commit_many(self, tnx):
        try:
            if len(self.sql_pool):
                for x in self.sql_pool:
                    print >> sys.stderr, x
                    tnx.execute(x)
                tnx._connection.commit()
            return True
        except Exception, e:
            tnx._connection.rollback()
            return False

    def execute(self, sql, callback = None, errorback = None):
        print "sql:", sql
        deferred = self.pool.runQuery(sql)
        if not callback or not errorback:
            return deferred
        else:
            deferred.addCallback(callback)
            deferred.addErrback(errorback)


